<?php
/**
 * Created by PhpStorm.
 * User: eric
 * Date: 2020/4/27
 * Time: 10:31
 */

namespace App\Http\Services;

use App\Exceptions\ServiceException;
use App\Exceptions\ServiceExceptionConstant;
use App\Http\Repositories\Daos\Platform\SystemSetDao;
use App\Http\Repositories\Redis\CacheDataRedis;
use App\Http\Traits\GlobalConstant;
use Illuminate\Http\Request;

class ConfigService extends BaseService
{

    protected $systemSetDao;

    public function __construct(SystemSetDao $systemSetDao)
    {
        $this->systemSetDao = $systemSetDao;
    }

    /**
     * 保存设置
     * @param $type
     * @param Request $request
     * @return bool
     */
    public function saveConfig($type, Request $request)
    {
        if (empty($type)) {
            throw new ServiceException(ServiceExceptionConstant::getErrorData('param_error'));
        }

        //有文件处理加到这里
        $aFiles = [];
        if (!empty($request->file())) {

            $aFileFields = ['start_bg', 'index_bg'];
            foreach ($aFileFields as $fileField) {
                $fileHandle   = $request->file($fileField);
                $default_disk = config('admin.upload.disk');
                if ($fileHandle) {
                    if (!is_array($fileHandle)) {
//                        $store_result = $fileHandle->store('adm_files');
                        $store_result = $fileHandle->store(config('admin.upload.directory.file'));
                        if (!$store_result) {
                            throw new ServiceException(ServiceExceptionConstant::getErrorData('image_save_failed'));
                        }
                        $fileUrl            = config('filesystems.disks.' . $default_disk . '.url') . $store_result;
                        $aFiles[$fileField] = $fileUrl;
                    } else {
                        foreach ($fileHandle as $value) {
//                            $store_result = $value->store('adm_files');
                            $store_result = $value->store(config('admin.upload.directory.file'));
                            if (!$store_result) {
                                throw new ServiceException(ServiceExceptionConstant::getErrorData('image_save_failed'));
                            }
                            $fileUrl = config('filesystems.disks.' . $default_disk . '.url') . $store_result;
                            $arr[]   = $fileUrl;

                        }
                        $aFiles[$fileField] = json_encode($arr);
                    }

                }
            }
        }

        //合并post和文件
        $aRequestData = array_merge($request->post(), $aFiles);
        if ($type == 'survey' && !empty($aRequestData)) {
            $this->changeSurveyTemplate($aRequestData);
        } else {
            foreach ($aRequestData as $oneKey => $oneVal) {
                //有分组转换数据的加在这里
                if (in_array($type, ['econ','upload'])) {
                    $oneVal = $this->fieldSave($type, $oneKey, $oneVal);
                }
                $configObj = $this->systemSetDao->getOne(['type' => $type, 'name' => $oneKey]);
                if ($configObj) {
                    $configObj->val = $oneVal;
                    $res            = $configObj->save();
                } else {
                    $aData = [
                        'type' => $type,
                        'name' => $oneKey,
                        'val'  => $oneVal
                    ];
                    $res   = $this->systemSetDao->save($aData);
                }
                if (!$res) {
                    throw new ServiceException(ServiceExceptionConstant::getErrorData('data_save_failed'));
                }
            }
        }

        //刷新缓存
        CacheDataRedis::getRedisInstance()->systemConfigCache();

        return true;
    }

    /**
     * 个别配置存储格式转换
     * @param $incType
     * @param $name
     * @param $value
     * @return mixed
     */
    public function fieldSave($incType, $name, $value)
    {
        switch ($incType) {
            case 'econ':
                foreach ($value as &$item) {
                    unset($item['_remove_']);
                }
                unset($item);
                $value = json_encode($value);
                break;
            case 'upload':
                $value = implode(GlobalConstant::DELIMITER_CHARACTER, array_slice($value,0,-1));
                break;
            default:
                break;
        }

        return $value;
    }

    public function changeSurveyTemplate($array)
    {
        $keyArray = ['base_info' => '人物基本信息', 'other_info' => '其他'];//对应SurveyTemplate配置的最外层键
        $return   = [];
        foreach ($array as $key => $item) {
            $arr = [];
            foreach ($item as $value) {
                $data['title']      = $value['字段名称'];
                $data['input_type'] = $value['字段类型'];
                $arr[]              = $data;
                unset($data);
            }

            $child['content'] = $arr;
            $child['title']   = $keyArray[$key];
            $return[$key]     = $child;
        }
        foreach ($return as $key => $item) {
            $configObj = $this->systemSetDao->getOne(['type' => 'survey', 'name' => $key]);
            if ($configObj) {
                $configObj->val = json_encode($item['content']);
                return $configObj->save();
            } else {
                $aData = [
                    'type' => 'survey',
                    'name' => $key,
                    'val'  => json_encode($item['content'])
                ];
                return $this->systemSetDao->save($aData);
            }
        }

    }

}
